import React from 'react';
import { useState,useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
// 引入二级路由组件
import Home from '../../router/home';
// 引入页面的css 文件
import '@/assets/css/dashboard.css';
// 导入图标
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    AppstoreOutlined,
    PieChartOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import { Layout, Menu, theme, Button, Modal, message } from 'antd';
import { Link,useHistory, useLocation  } from 'react-router-dom'
import { getusername, testjwt } from '../../api/dashboard';
const { Header, Sider, Content } = Layout;
const Dashboard = () => {
    // 控制左侧菜单折叠变量
    const [collapsed, setCollapsed] = useState(false);
    const {
        token: { colorBgContainer },
    } = theme.useToken();
    // 获取redux 仓库中的store保存的菜单数据acl
    const { acl } = useSelector((state) => state)
    // 左侧menu 菜单的函数
    function getItem(label, key, icon, children, type) {
        return {
            key,
            icon,
            children,
            label,
            type,
        };
    }
    const items = [];
    acl.map((item) => {
        if (item.children.length != 0) {
            // 说明该菜单有二级菜单
            items.push(getItem(item.auth_name, item.auth_path, <AppstoreOutlined />, item.children.map((item1) => {
                // 只渲染 is_nav为1 的菜单项
                // 渲染二级菜单
                if (item1.is_nav == 1) {
                    return getItem(<Link to={item1.auth_path}>{item1.auth_name}</Link>, item1.auth_path)
                }
            })))
        } else {
            // 渲染一级菜单
            items.push(getItem(<Link to={item.auth_path}>{item.auth_name}</Link>, item.auth_path, <PieChartOutlined />))
        }
    })

    // 定义阻止翻墙功能
    const [username, setusername] = useState({})
    const [islogin, setislogin] = useState(false)
    useEffect(() => {
        // 获取用户信息接口
        getusername().then(res => {
            if (res.data.errNo == 0) {
                setusername(res.data.accountInfo)
            }
        })

        // 验证token,查看用户是否登录接口,防跳墙功能
        testjwt().then(res => {
            if (res.data.errNo != 0) {
                message.error('请登录', 1, () => {
                    his.push('/login')
                })
            } else {
                setislogin(true)
            }
        })

    }, [])

   
    // 定义退出登录函数
    const dispatch = useDispatch();
    const his = useHistory()
    const loginOut = () => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '是否退出登录',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                // 清除登录时token,user，jwt等信息
                localStorage.removeItem('jwt')
                dispatch({ type: 'updateacl', payload: [] });
                localStorage.removeItem('persist:useracl');
                //返回登录页
                setTimeout(() => {
                    his.push('/login')
                }, 500)

            }
        });
    }
    // 设置默认选中的菜单项defaultSelectedKeys key 对应的path 路径
    const loc = useLocation();
    return (
            <>
            {islogin ? <Layout>
                    <Sider trigger={null} collapsible collapsed={collapsed}>
                        <div className="logo"></div>
                        <Menu
                            theme="dark"
                            mode="inline"
                            items={items}
                            defaultSelectedKeys={[loc.pathname]}
                            //设置默认打开的一级菜单
                            defaultOpenKeys={[loc.pathname.substring(0, loc.pathname.lastIndexOf('/'))]}
                        />
                    </Sider>
                    <Layout className="site-layout">
                        <Header
                            style={{
                                padding: 0,
                                background: colorBgContainer,
                                display: 'flex',
                                alignItems: 'center',
                            }}
                        >
                            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                                className: 'trigger',
                                onClick: () => setCollapsed(!collapsed),
                            })}
                            <div className='top'>
                                {/* 显示用户名和角色 */}
                                <span>您好,{username.username}/{username.role}</span>
                                {/* 注销登录按钮 */}
                                <Button onClick={loginOut}>注销登录</Button>
                            </div>
                        </Header>
                        <Content
                            style={{
                                margin: '24px 16px',
                                padding: 24,
                                minHeight: 280,
                                background: colorBgContainer,
                                overflow:'auto'
                            }}
                        >
                            {/* 改成二级路由组件的坑 */}
                            <Home></Home>
                        </Content>
                    </Layout>
                </Layout> : <></>
             }
        </>
    );
}

export default Dashboard;